<!--
/**
* @name OperateTable
* @description 新增和编辑表格
* @author wind-lc
* @date 2020-05-11
* @param {Boolean} operateVisible 是否打开新增和编辑抽屉
* @param {Object} operateData 新增和编辑抽屉数据
* @param {Event} handleVisible 关闭新增和编辑抽屉
* @example <operate-table :operateVisible="" :operateData="" @handleVisible=""></operate-table>
*/
-->
<template>
  <a-drawer :title="title"
            :wrapClassName="isDetails?'drawer-box hidden-drawer-footer':'drawer-box'"
            :width="800"
            :visible="operateVisible"
            :destroyOnClose="true"
            @close="handleVisible">
    <div class="drawer-wrap">
      <form-loading :formLoadingVisible="formLoadingVisible"></form-loading>
      <!-- 基本信息 -->
      <h3 class="form-title">基本信息</h3>
      <a-form-model ref="form"
                    :rules="rules"
                    :model="form"
                    :hideRequiredMark="isDetails"
                    :label-col="labelCol"
                    :wrapper-col="wrapperCol">
        <a-row :gutter="16">
          <a-col :span="12">
            <a-form-model-item label="角色编码"
                               prop="code">
              <a-input v-model="form.code"
                       v-show="!isDetails"
                       placeholder="请输入角色编码"
                       :maxLength="20">
              </a-input>
              <span v-show="isDetails">{{form.code}}</span>
            </a-form-model-item>
          </a-col>
          <a-col :span="12">
            <a-form-model-item label="角色名称"
                               prop="name">
              <a-input v-model="form.name"
                       v-show="!isDetails"
                       placeholder="请输入角色名称"
                       :maxLength="20">
              </a-input>
              <span v-show="isDetails">{{form.name}}</span>
            </a-form-model-item>
          </a-col>
        </a-row>
        <a-row :gutter="16">
          <a-col :span="12">
            <a-form-model-item label="状态"
                               prop="status">
              <a-switch v-model="status"
                        :disabled="isDetails"
                        :checked-children="statusText[0].name"
                        :un-checked-children="statusText[1].name" />
            </a-form-model-item>
          </a-col>
        </a-row>
        <a-row :gutter="16">
          <a-col :span="24">
            <a-form-model-item label="备注"
                               :label-col="{ span: 3}"
                               :wrapper-col="{ span: 20 }"
                               prop="remark">
              <a-input type='textarea'
                       v-show="!isDetails"
                       :autoSize="{minRows: 5,maxRows: 5}"
                       v-model="form.remark"
                       :maxLength="100"
                       placeholder="请输入备注">
              </a-input>
              <span v-show="isDetails">{{form.remark || '无'}}</span>
            </a-form-model-item>
          </a-col>
        </a-row>
      </a-form-model>
      <!-- 基本信息 -->
      <!-- 菜单权限 -->
      <h3 class="form-title">菜单权限</h3>
      <a-tree v-model="checkedKeys"
              checkable
              :disabled="isDetails"
              :tree-data="treeData" />
      <!-- 菜单权限 -->
      <div class="drawer-footer">
        <a-button key="back"
                  icon="close-circle"
                  @click="handleVisible">取消</a-button>
        <a-button key="submit"
                  icon="save"
                  type="primary"
                  :loading="confirmLoading"
                  @click="handleConfirm">提交</a-button>
      </div>
    </div>
  </a-drawer>
</template>
<script>
import { Drawer, FormModel, Row, Col, Input, Tree, Button, Switch } from 'ant-design-vue'
import { insertSelective, getHnResourceList, getHnRoleById, updateByPrimaryKeySelective } from '@/request/api/permissionManagement/roleManagement'
import { regexConstants, validators } from '@/utils/validate'
export default {
  name: 'OperateTable',
  components: {
    ADrawer: Drawer,
    AFormModel: FormModel,
    AFormModelItem: FormModel.Item,
    ARow: Row,
    ACol: Col,
    AInput: Input,
    ATree: Tree,
    AButton: Button,
    ASwitch: Switch
  },
  props: {
    // 是否打开新增和编辑抽屉
    operateVisible: {
      type: Boolean,
      required: true
    },
    // 新增和编辑抽屉数据
    operateData: {
      type: Object,
      required: true
    }
  },
  data () {
    return {
      // 标题
      title: '',
      // 表单
      form: {
        code: '',
        name: '',
        status: '',
        remark: ''
      },
      // 状态
      status: true,
      // 状态数据字典
      statusText: [
        {
          name: ''
        },
        {
          name: ''
        }
      ],
      // 表单布局
      labelCol: { span: 6 },
      wrapperCol: { span: 16 },
      // 校验
      rules: {
        code: [
          {
            required: true,
            message: '请输入角色编码',
            trigger: 'change'
          },
          {
            pattern: regexConstants.character,
            validator: validators.newValidate,
            message: '不能含有中文',
            trigger: 'change'
          }
        ],
        name: [
          {
            required: true,
            message: '请输入角色名称',
            trigger: 'change'
          }
        ]
      },
      // 表单加载loading
      formLoadingVisible: false,
      // 菜单选中项
      checkedKeys: [],
      // 菜单权限树
      treeData: [],
      // 提交loading
      confirmLoading: false,
      // 编辑id
      editId: ''
    }
  },
  watch: {
    // 监听抽屉打开关闭
    operateVisible: {
      handler (newV, oldV) {
        this.statusText = this.operateData.dataDictionary.status
        // 打开抽屉
        if (newV) {
          // 新增
          if (this.operateData.type === 'add') {
            this.title = '新增角色'
            this.formLoadingVisible = true
            this.getMenuPermission()
          }
          // 编辑
          if (this.operateData.type === 'edit' || this.operateData.type === 'view') {
            this.title = '编辑角色'
            if (this.operateData.type === 'view') {
              this.title = '角色详情'
            }
            this.formLoadingVisible = true
            this.editId = this.operateData.row.id
            this.status = this.operateData.row.status === '1'
            this.getMenuPermission()
            // 数据写入表单
            for (const item in this.form) {
              this.form[item] = this.operateData.row[item]
            }
          }
        }
      }
    }
  },
  computed: {
    isDetails () {
      return this.operateData.type === 'view'
    }
  },
  methods: {
    // 获取角色菜单权限
    getRoleMenuPermission () {
      getHnRoleById({
        id: this.editId
      }).then(res => {
        if (res.code === '0') {
          this.checkedKeys = res.data.resIdList
        }
        this.formLoadingVisible = false
      }).catch(error => {
        this.formLoadingVisible = false
        console.log(error)
      })
    },
    // 获取菜单权限列表
    getMenuPermission () {
      getHnResourceList({}).then(res => {
        if (res.code === '0') {
          this.treeData = res.data
          if (this.operateData.type === 'edit' || this.operateData.type === 'view') {
            this.getRoleMenuPermission()
          } else {
            this.formLoadingVisible = false
          }
        }
      }).catch(error => {
        this.formLoadingVisible = false
        console.log(error)
      })
    },
    // 选中行
    selectedRowChange (selectedRowKeys) {
      this.selectedRowKeys = selectedRowKeys
    },
    // 确定按钮
    handleConfirm () {
      this.$refs.form.validate(valid => {
        if (valid) {
          this.confirmLoading = true
          if (this.operateData.type === 'add') {
            // 新增角色
            const param = Object.assign({}, this.form)
            param.resIdList = this.checkedKeys
            param.createName = JSON.parse(localStorage.getItem('ycloud-operate-user_info')).name
            param.status = this.status ? this.statusText[0].value : this.statusText[1].value
            insertSelective(param).then(res => {
              this.confirmLoading = false
              if (res.code === '0') {
                this.$message.success('新增成功!')
                this.handleConfirmVisible()
              }
            }).catch(error => {
              this.confirmLoading = false
              console.log(error)
            })
          }
          if (this.operateData.type === 'edit') {
            // 编辑角色
            this.$refs.form.validate(valid => {
              if (valid) {
                const param = Object.assign({}, this.form)
                param.id = this.editId
                param.resIdList = this.checkedKeys
                param.createName = JSON.parse(localStorage.getItem('ycloud-operate-user_info')).name
                param.status = this.status ? this.statusText[0].value : this.statusText[1].value
                updateByPrimaryKeySelective(param).then(res => {
                  this.confirmLoading = false
                  if (res.code === '0') {
                    this.$message.success('编辑成功!')
                    this.handleConfirmVisible()
                  }
                }).catch(error => {
                  this.confirmLoading = false
                  console.log(error)
                })
              }
            })
          }
        }
      })
    },
    // 关闭抽屉
    handleVisible () {
      if (!this.isDetails) {
        this.$confirm({
          title: '放弃本次操作并清空表单?',
          okText: '是',
          okType: 'danger',
          cancelText: '否',
          onOk: () => {
            this.form = {
              code: '',
              name: '',
              status: '',
              remark: ''
            }
            this.treeData = []
            this.checkedKeys = []
            this.$emit('update:operateVisible', false)
          }
        })
      } else {
        this.form = {
          code: '',
          name: '',
          status: '',
          remark: ''
        }
        this.treeData = []
        this.checkedKeys = []
        this.$emit('update:operateVisible', false)
      }
    },
    // 提交关闭抽屉
    handleConfirmVisible (text) {
      this.form = {
        code: '',
        name: '',
        status: '',
        remark: ''
      }
      this.treeData = []
      this.checkedKeys = []
      this.editId = ''
      this.$emit('handleVisible', false)
    }
  }
}
</script>
<style lang="scss">
</style>
